from openai import OpenAI
import re
import db


message_table = {}
my_model='deepseek-r1'

client = OpenAI(
    base_url='https://dashscope.aliyuncs.com/compatible-mode/v1',
    api_key='sk-318c14013f094d5fb229befdc83ef963',
)


def clean_response(content):
    content = re.sub(r'\[.*?\]', '', content, flags=re.DOTALL)
    # 去除Markdown加粗和倾斜标记
    content = re.sub(r'\*\*\*', '', content)
    content = re.sub(r'\*\*', '', content)
    content = re.sub(r'\*', '', content)
    # 去除行首的#和-
    content = re.sub(r'^\t*[#-]+', '', content, flags=re.MULTILINE)

    content = re.sub(r'\n+', '\n', content)
    content = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL)
    return content.strip()

def pre_handle_message(historys):
    msgs = []
    for history in historys:
        print(history)
        msg = {
            "role": history['role'],
            "content": history['content'].replace("@Sylvester﹌", "")
        }
        msgs.append(msg)
    return msgs

def chat_sender(user,sender,status):
    historys = db.get_history_nickname(user,sender)
    # 如果status为1，只取最后一条消息
    if status == 1:
        historys = historys[:1]
    try:
        response = client.chat.completions.create(
            model=my_model,
            messages=pre_handle_message(historys))
        content = response.choices[0].message.content
        content = clean_response(content)
        return content
    except Exception as e:
        print(f"Error: {e}")
        return "抱歉，我遇到了一个错误，请稍后再试。"

   





